// pages/index/index.js

// 使用云数据库
const db = wx.cloud.database();

// 引入获取当前时间类
const util = require('util.js');

// 定义全局对象
let app = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 签到卡id
        Signin_id:'',

        // 签到详细信息
        SigninInfo: [],

        // 签到按钮状态（'请选择日期'、'打卡'、'补签'、'无法打卡'、'今日已打卡'）
        btn_state:'请选择日期',

        // 已打卡图标显示标志
        success:false,

        id: null,
    name: "",
    icon: "",
    disabledFlag: true,
    totalDays:0,
    monthDays:0,
    SigninInfo: {},
    currentDate: null,
    currentMonth: null,
    currentYear: null,
    nowYear: new Date().getFullYear(),
    nowMonth: new Date().getMonth(),
    nowDate:new Date().getDate(),
    punchCardDateArr: [] ,//用于存放当月打卡日期-日

        // 进入签到界面标志
        Signin: false,

        // 签到成功标志 
        isSignin:false,

        // 日历样式数据
        SigninDay: [
            {month: 'current', day: '2', color: 'white', background: '#AAD4F5'},
            {month: 'current',day:'8',background:'#AAD4F5',color:'white'}
          ],

        //临时日历样式数据
        temp_SigninDay: [
            {date: '', color: '', background: ''},
          ],
            

        topimageItems: [
            'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/index_swiper/index_swiper1.png',
            'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/index_swiper/index_swiper3.png',
            'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/index_swiper/index_swiper2.png',
        ],
        // temp_hotList:[],

        communityhotList:[],
        lawshotList:[],
        farminghotList:[],
        culture:[
            {id: 1,imgsrc: 'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/index_swiper/index_swiper1.png',title:"国画鉴赏课", headphoto:'https://pic.rmb.bdstatic.com/aa9e462d0f19b097bbd790940ec78c71.jpeg', likenum:99999},
            {id: 2,imgsrc: 'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/index_swiper/index_swiper2.png',title:"广场舞教学", headphoto:'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/community-headphoto/community-headphoto2.png', likenum:8888},
            {id: 3,imgsrc: 'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/index_swiper/index_swiper3.png',title:"书法课",  headphoto:'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/community-headphoto/community-headphoto3.png', likenum:666},
        ],
        agricultural:[
            {id: 1,imgsrc: 'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/index_swiper/index_swiper1.png',title:"农技教学1",info:"本课程介绍了哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈", headphoto:'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/community-headphoto/community-headphoto1.png', PageView:9999999999},
            {id: 2,imgsrc: 'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/index_swiper/index_swiper2.png',title:"农技教学2",info:"本课程介绍了哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈", headphoto:'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/community-headphoto/community-headphoto2.png', PageView:88888},
        ],
        class:[
            {id: 1,imgsrc: 'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/index_swiper/index_swiper1.png',title:"国画鉴赏课",collection:"31313"},
            {id: 2,imgsrc: 'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/index_swiper/index_swiper2.png',title:"广场舞教学",collection:"12355"},
            {id: 3,imgsrc: 'cloud://cloud1-0gi6arka36ad54a9.636c-cloud1-0gi6arka36ad54a9-1310110789/village characteristic/index_swiper/index_swiper3.png',title:"书法课",collection:"5343"},
        ]
    },

    //预览图片，放大预览
    preview(event) {
        console.log(event)
        let index = event.currentTarget.dataset.index
        wx.previewImage({
            // 当前显示图片的http链接
            current: this.data.topimageItems[index], 
            // 需要预览的图片http链接列表
            urls: this.data.topimageItems 
        })
    },

    handleImgChange: function (e) {
        this.setData({
            currentIndex: e.detail.current
        })
    },

    // 打开签到页面函数
    openSigninbox:function(){
        let that = this
        if(!wx.getStorageSync('login')){
            wx.showModal({
                title: '温馨提示',
                content: '请您先登录,否则无法进行打卡',
                success(res) {
                    // 如果用户点击了确定按钮
                    if (res.confirm){
                        wx.switchTab({
                            url:'/pages/user/user'
                        })
                    }
                    else return
                }
            })
        }
        else if(that.data.isSignin === true){
            // wx.showToast({
            //   title: '今日已打卡',
            // //   icon:'error',
            //   duration:2000
            // })
            that.setData({
                success:true
            })
            setTimeout(function () {
                that.setData({
                    success:false
                })
            },2000)
        }
        else{
            that.setData({
                Signin:true,
            })
        }
    },

    // 关闭签到页面函数
    closewindows:function(){
        this.setData({
            Signin:false,
        })
    },
    
    //给点击的日期设置一个背景颜色
    dayClick: function (event) {
        let Today_date = util.formatTime(new Date());
        console.log(Today_date)
        let Today_day = util.formatDay(new Date());
        console.log(Today_day)
        let clickDate = event.detail.year+'/'+event.detail.month+'/'+event.detail.day;
        let Day = event.detail.day
        if(Today_date != clickDate){
            wx.showToast({
              title: '只能打卡今天哦',
              icon: 'error',
              duration: 2000,
            })
            return
        }
        let Day_tostring = parseInt(Day)
        // console.log(clickDay)
        // console.log(event.detail)
        let changeBgColor = `SigninDay[0].color`;
        let changeBg = `SigninDay[0].background`;
        let changeDay = `SigninDay[0].day`;
    
        let arr = this.data.SigninDay
        arr.push({month: 'current',day:'10',background:'#AAD4F5',color:'white'})
        this.setData({
            SigninDay:arr
        })
        // this.setData({
        // [changeDay]: day,
        // [changeBg]:"rgba(255,255,255,0)",
        // [changeBgColor]:"white",
        // })
    },
    
    // 加载数据函数
    loadData:function(){
        let that = this
        db.collection('hot_data').orderBy('createTime','desc').limit(1).get().then(async res =>{
            console.log(res.data[0])
            that.setData({
                communityhotList:res.data[0].community_rank,
                lawshotList:res.data[0].laws_rank,
                farminghotList:res.data[0].farming_rank
            })
        })
    },

    // 跳转社区热门页面
    jumpCommunity:function(){
        app.globalData.state = 'hot_tab'
        wx.switchTab({
            url: '/pages/community/community',
        })
    },

    // 跳转学习农技教学页面
    jumpStudy_farming:function(){
        app.globalData.state = 'farming_tab'
        wx.switchTab({
            url: '/pages/study/study',
        })
    },

    // 跳转学习普法栏目页面
    jumpStudy_laws:function(){
        app.globalData.state = 'laws_tab'
        wx.switchTab({
            url: '/pages/study/study',
        })
    },

    // 获取子组件数据函数
    getObj(e) {
        // console.log("获取子组件的数据", e);
        this.setData({
            currentDate: e.detail.currentDate,
            currentMonth: e.detail.currentMonth,
            currentYear: e.detail.currentYear,
        })
        this.getSigninInfo(e.detail.currentYear, e.detail.currentMonth - 1)
    },
    
    // 获取当月的打卡数据
    getSigninInfo(year, month) {
        let that =this
        // 注意month范围 0-11，0代表1月
        let openid =  wx.getStorageSync('openid')
        db.collection('Signin_List').where({
            _openid:openid,
        }).get().then(res => {
            // console.log("从数据库获取签到数据===", res)
            let Signin_TimeArr = res.data[0].Signin_List

            let flag = true
            // 判断能否打卡
            // 页面初始化时，未点击任何日期
            if(!that.data.currentDate){
                // 打卡按钮禁用
                flag = true
                that.setData({
                    btn_state:'请选择日期'
                })
                // console.log("哈哈哈",currentDate)
            }
            // 当前点击的日期在今天之后
            else if ((year==that.data.nowYear && month>that.data.nowMonth)||(year==that.data.nowYear && month==that.data.nowMonth &&that.data.currentDate>that.data.nowDate) ) {
                // 打卡按钮禁用
                flag = true
                that.setData({
                    btn_state:'无法打卡'
                })
            }
            // 当前点击的日期在今天之前
            else if((year==that.data.nowYear && month<that.data.nowMonth)||(year==that.data.nowYear && month==that.data.nowMonth &&that.data.currentDate<that.data.nowDate)){
                flag = false
                // for(let i = 0;i<Signin_TimeArr.length;i++){
                //     let Year = Signin_TimeArr[i].slice(0,4)
                //     let i1 = Signin_TimeArr[i].indexOf("-")
                //     let i2 = Signin_TimeArr[i].lastindexOf("-")
                //     let Month = Signin_TimeArr[i].slice(i1+1,i2)
                //     let Day = Signin_TimeArr[i].slice(i2)
                //     console.log(Year,Month,Day)
                //     if(Year == that.data.currentYear && Month == that.data.nowMonth ){
                //         flag = true
                //         that.setData({
                //             btn_state:'已补签'
                //         })
                //         break
                //     }
                // }
                // let Year = Signin_TimeArr[]
                that.setData({
                    btn_state:'补签'
                })
            }
            // 点击的日期是今天
            else{
                flag = false 
                that.setData({
                    btn_state:'打卡'
                })
            }

            that.setData({
                Signin_id:res.data[0]._id,
                SigninInfo: Signin_TimeArr,
                // punchCardDateArr: dateArr,
                disabledFlag: flag,
                totalDays:Signin_TimeArr.length,
                totalScore:Signin_TimeArr.length*2,
                currentScore:Signin_TimeArr.length*2
                // monthDays:dateArr.length
            })
        }).catch(err => {
            console.log(err);
        })
    },

    // 点击打卡函数
    punchCard:function() {
        let that = this
        if(that.data.btn_state === '无法打卡'){
            wx.showToast({
                title: '抱歉无法提前打卡',
                icon: 'none',
                // duration: 2000,
            })
            return
        }
        else if(that.data.btn_state == '请选择日期'){
                wx.showToast({
                    title: '请先选择日期',
                    icon: 'none',
                    duration: 2000,
                })
                return
        }
        else{
            let currentTime = {
                date: this.data.currentYear.toString()+'-'+this.data.currentMonth.toString()+'-'+this.data.currentDate.toString()  
            }
            // console.log(currentTime)
            let id =that.data.Signin_id
            db.collection('Signin_List').doc(id).update({
                data: {
                    Signin_List:db.command.unshift(currentTime)
                },
                success: res => {
                    let openid =  wx.getStorageSync('openid')
                    db.collection('Signin_List').where({
                        _openid:openid,
                    }).get().then(res => {
                        if(that.data.btn_state == '补签'){
                            wx.showToast({
                                title: '恭喜你补签成功',
                            })
                            that.setData({
                                totalDays:res.data[0].Signin_List.length,
                                totalScore:res.data[0].Signin_List.length*2,
                                currentScore:res.data[0].Signin_List.length*2
                            })
                        }
                        else{
                            wx.showToast({
                                title: '恭喜你打卡成功',
                            })
                            that.setData({
                                totalDays:res.data[0].Signin_List.length,
                                totalScore:res.data[0].Signin_List.length*2,
                                currentScore:res.data[0].Signin_List.length*2,
                                isSignin:true,
                                btn_state:'今日已打卡'
                            })
                        }
                        // that.setData({
                        //     currentPunchCardDate:
                        // })

                        // this.getSigninInfo(this.data.currentYear, this.data.currentMonth - 1)
                    })
                },
                fail: err => {
                    wx.showToast({
                    icon: 'none',
                    title: '打卡失败了'
                    })
                }
            })
        }    
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options){
        // 点击外部分享链接后进入小程序后判断url
        if(options.url){
            let url = decodeURIComponent(options.url);
            wx.navigateTo({
                url
            })
        }
        this.loadData()
        // console.log(options);
        // this.setData({
        //   id: options.id,
        //   name: options.name,
        //   icon: options.icon
        // })
        var nowYear = new Date().getFullYear()
        var nowMonth = new Date().getMonth()
        wx.nextTick(() => {
          this.getSigninInfo(nowYear, nowMonth)
        })
    
 
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})